/**
 * 
 */

var rules = {
	name : {
		identifier : 'name',
		rules : [ {
			type : 'empty',
			prompt : '请填写分类名称'
		} ]
	},
	orderIndex: {
		identifier: 'orderIndex',
		rules: [{
			type: 'integer[1..50]',
			prompt: '请输入1-50之间任意整数'
		}]
	}
};

var testEditor;
$(function () {
	//初始化markdown editor
    testEditor = editormd("test-editormd", {
        height: "95vh",
        path: full_path + "lib/",
        htmlDecode: "style,script,iframe",
        sequenceDiagram: true,
        saveHTMLToTextarea: true,
        imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL: full_path + "file/file_upload/upload_image.jhtml"
    });
    
    //验证新增category的合法性
    $("#categoryForm").form({
    	on: 'blur',
    	fields: rules,
    	inline: true,
    	onValid: function(){
    		//验证分类的唯一性
    		var name = $(this).attr("name");
    		if(name == 'name'){
    			ajaxValidate(name,$(this).val());
    		}
    	}
    });
});


//验证分类的唯一性
function ajaxValidate(selector,value){
	var flag = false;
	$.ajax({
		url: 'category/unique.jhtml',
		type: 'post',
		data: {name: selector,value: value},
		dataType: 'json',
		async: false,
		success: function(data){
            if (data['code'] == "1") {
                $("input[name=" + selector + "]").next().css("visibility", "visible");
                $("#categoryForm").form("remove prompt", selector, data['msg']);
                flag = true;
            } else {
                $("input[name=" + selector + "]").next().css("visibility", "hidden");
                $("#categoryForm").form("add prompt", selector, data['msg']);
                flag = false;
            }
		}
	});
	return flag;
}

//初始化标签选择
$("#selection-tag").dropdown({
	apiSettings: {url: "../p/data_dict/query.jhtml?type=1&name={query}"},
	fields: {remoteValues: 'data',name: 'name',value: 'val'},
	maxSelections: 6
});

//初始化文章分类目录
$("#selection-category").dropdown({
	apiSettings: {url: "../v/category/query.jhtml?qryName={query}"},
	fields: {remoteValues: 'data',name: 'name',value: 'id'}
});


//弹出新增category框
$(".ui.modal").modal("attach events","#add-category");

//绑定提交category
$(".ui.primary.button").click(function(){
	var flag = false;
	$(this).addClass('loading');
	
	//验证表单规则
	flag = $("#categoryForm").form({
        on: 'blur',
        fields: rules,
        inline: true
    }).form("is valid");
 
	 //验证不通过
	 if(!flag){
	     $("#category-message").addClass("visible").text("填写文章分类有误");
		 return false;
	 }
	
	//再次验证唯一性
	if(!ajaxValidate('name',$("input[name=name]").val())){
		return false;
	}
	 
	 //提交
	 $.ajax({
		 url: 'category/insert.jhtml',
		 type: 'post',
		 data: $("#categoryForm").serialize(),
		 dataType: 'json',
		 success: function(data){
			 if(data['code'] == '1'){
				 $(".ui.primary.button").removeClass('loading');
				 $(".ui.modal").modal("hide");
			 }else{
				 $(".ui.primary.button").removeClass('loading');
				 $("#category-message").addClass("visible").text(data['msg']);
			 }
		 }
	 });
});



//发布文章
function publicArticle(){
	var arules = {
		title : {
			identifier : 'title',
			rules : [ {
				type : 'empty',
				prompt : '请填写文章标题'
			}, {
				type : 'maxLength[50]',
				prompt : '标题最长不超过50个字符'
			} ]
		},
		categoryId : {
			identifier : 'categoryId',
			rules : [ {
				type : 'empty',
				prompt : '请选择文章类别'
			} ]
		},
		tags : {
			identifier : 'tags',
			rules : [ {
				type : 'empty',
				prompt : '请选择标签'
			} ]
		},
		summary : {
			identifier : 'summary',
			rules : [ {
				type : 'empty',
				prompt : '请填写文章概述'
			} ]
		}
	};
	
	var flag = $("#article-form").form({
		on: 'blur',
    	fields: arules,
    	inline: true
	}).form("is valid");
	
	
	if(!flag){
		return false;
	}
	
	//判读是否输入正文
	var content = $("textarea[name='content']").val();
	if(!content){
		$("#article-message").addClass("visible").text("请键入文章正文");
		return false;
	}
	
	//弹出进行中的遮罩
	$(".ui.inverted.page.dimmer").addClass("active");
	$("textarea[name='htmlContent']").val(testEditor.getPreviewedHTML());
	//保存文章
	$.ajax({
		url:  'insert.jhtml',
		type: 'post',
		data: $("#article-form").serialize(),
		//data: {title: $("input[name='title']").val(),categoryId: $("input[name='categoryId']").val(),tags: $("input[name='tags']").val(),content: testEditor.getMarkdown(),htmlContent: testEditor.getPreviewedHTML(),summary: $("textarea[name='summary']") },
		dataType: 'json',
		success: function(data){
			if(data['code'] == '1'){
				console.log(data);
				$(".ui.text.loader").text("文章发布成功,正在跳转...");
				setTimeout(function(){
					window.location.href = "../p" + user_name + "/detail/" + data['data'] + ".jhtml";
				}, 1000);
			}else{
				$(".ui.inverted.page.dimmer").removeClass("active");
				$("#article-message").addClass("visible").text(data['msg']);
			}
		}
			
	});
}


